package one.coder.netty.chapter.fifteen.extend;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel.MapMode;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

/**
 * @author lihzh
 * @alia OneCoder
 * @blog http://www.coderli.com
 */
public class BigFileRecieveServerHandler extends SimpleChannelHandler {

	private File file = new File("F:/CentOS_5.4_Final.iso");
	private RandomAccessFile raf;
	private AtomicLong index = new AtomicLong();
	private AtomicInteger count = new AtomicInteger();

	public BigFileRecieveServerHandler() {
		try {
			if (!file.exists()) {
				file.createNewFile();
			} else {
				file.delete();
				file.createNewFile();
			}
			raf = new RandomAccessFile(file, "rw");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e)
			throws Exception {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
//				synchronized (raf) {
//					ChannelBuffer buffer = (ChannelBuffer) e.getMessage();
//					int length = buffer.readableBytes();
//					MappedByteBuffer mapBuffer = null;
//					try {
//						mapBuffer = raf.getChannel().map(MapMode.READ_WRITE,
//								index.get(), length);
//					} catch (IOException e1) {
//						e1.printStackTrace();
//					}
//					mapBuffer.put(buffer.array());
//					mapBuffer.force();
//					buffer.clear();
//					index.addAndGet(length);
//					System.out.println("Read bytes: " + length);
//					System.out.println("Index: " + index);
//				}
				System.out.println(count.addAndGet(1));
			}
		}).start();
	
	}
}
